package com.glsc.ngateway.common.base.utils;

/*
 *
 * Copyright (c) 2001-2017 泛微软件.
 * 泛微协同商务系统,版权所有.
 *
 */

import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.SystemConfigRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Objects;

/**
 * AES加密解密
 *
 * @author chengf
 */
@Component
public class OaAESEncryptUtil {
    /**
     * 系统集成日志对象，用于统一输出日志到系统集成日志文件中。
     */
    private static Logger logger = LoggerFactory.getLogger(OaAESEncryptUtil.class);

    private static SystemConfigRepository systemConfigRepository;

    @Resource
    public void setSystemConfigRepository(SystemConfigRepository systemConfigRepository) {
        OaAESEncryptUtil.systemConfigRepository = systemConfigRepository;
    }

    private static final String CONFIG_OA_SECURE_KEY_DECODE = "OA_SECURE_KEY_DECODE";
    private static final String CONFIG_OA_SECURE_KEY_ENCODE = "OA_SECURE_KEY_ENCODE";
    public static final String CONFIG_OA_SECURE_KEY_SPLIT = "OA_SECURE_KEY_SPLIT";


    public static void main(String[] args) {
//        oaAesEncryptUtil.setPwd("88888888");

        String decode = OaAESEncryptUtil.decode("172D860A350537099684A654FFC0DE02C83D4360930B5F8D9A8355A6A956E0DB4283F0FCC9572B5DC57340B041848758");
        System.out.println("decode=" + decode);

        OaAESEncryptUtil oaAesEncryptUtil2 = new OaAESEncryptUtil();

        String decode2 = OaAESEncryptUtil.decode("172D860A350537099684A654FFC0DE02C83D4360930B5F8D9A8355A6A956E0DB4283F0FCC9572B5DC57340B041848758");
        System.out.println("decode=" + decode2);
    }

    /**
     * 将传入的明文转换为密文
     *
     * @param str 明文字符串
     * @return 加密后的密文
     */
    public static String encode(String str) {
        byte[] result = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            String pwd = null;
            SystemConfig byConfigCode = systemConfigRepository.findByConfigCode(CONFIG_OA_SECURE_KEY_ENCODE);
            pwd = Objects.isNull(byConfigCode) ? "ecology9" : byConfigCode.getConfigValue();
            random.setSeed(pwd.getBytes());
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] byteContent = str.getBytes();
            result = cipher.doFinal(byteContent);

        } catch (Exception e) {
            logger.error("加密异常！", e);
            return null;
        }

        return parseByte2HexStr(result);
    }

    /**
     * 将传入的密文转换为明文
     *
     * @param str 密文字符串
     * @return 解密后的明文
     */
    public static String decode(String str) {
        byte[] result = null;
        try {
            byte[] content = parseHexStr2Byte(str);
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            String pwd = null;
            SystemConfig byConfigCode = systemConfigRepository.findByConfigCode(CONFIG_OA_SECURE_KEY_DECODE);
            pwd = Objects.isNull(byConfigCode) ? "88888888" : byConfigCode.getConfigValue();
            random.setSeed(pwd.getBytes());
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            result = cipher.doFinal(content);

        } catch (Exception e) {
            logger.error("解密异常！{}", e.getMessage());
            return null;
        }

        return new String(result);
    }

    /**
     * 设置加密和解密的密钥
     *
     * @param pwd 加密密钥
     * @return true：成功，false：失败
     */
    public boolean setPwd(String pwd) {
//        this.pwd = pwd;
        return true;
    }

    /**
     * 设置加密和解密的向量
     *
     * @param iv 加密向量
     * @return true：成功，false：失败
     */
    public boolean setIv(String iv) {
        return true;
    }

    /**
     * 将二进制转换成十六进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将十六进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
